<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useStore } from "vuex";
import { addTalk, getTalkList } from "@/api/talk.js";
import { ChangeBaseToBlob } from "@/utils/changeBaseToBlob.js";
import NewsItem from "../../components/NewsItem.vue";
let messageRef = ref();
const newsList = ref([]);
const talkTypeList = ref([]);
const LinkList = ref([]);
const ImgList = ref([]);
const groupId = ref(null);
const showEmoji = ref(false);
const showLink = ref(false);
const textareaisFocus = ref(false);
let qzText = ref("请选择圈子");
let qzId = ref();
const link = ref("");
const $store = useStore();

onMounted(() => {
  getNewsList();
  getTalkType();
});

// 计算属性
const TalkEnumList = computed(() => {
  return $store.state.talkEnumTypeList;
});

const getNewsList = async (params) => {
  if (params && params.groupId) {
    const res = await getTalkList(params);
    console.log(res, "getTalk");
    newsList.value = res.data;
  } else {
    const res = await getTalkList();
    console.log(res, "getTalk");
    newsList.value = res.data;
  }
};
// 获取枚举类型
const getTalkType = async () => {
  talkTypeList.value = await $store.dispatch("getEnumType", "talk-type");
};

const getEmoji = (url) => {
  console.log(url, "url");
  handleChangeEmoji();
  createImg(url);
  console.log(messageRef.value, "ref");
};

const createImg = (url) => {
  const img = document.createElement("img");
  img.src = url;
  messageRef.value.appendChild(img);
  // 创建一个新的 Range 对象
  const range = new Range();
  // 将 Range 对象设置为 messageRef 的末尾
  range.selectNodeContents(messageRef.value);
  range.collapse(false);
  // 获取当前的 Selection 对象
  const selection = window.getSelection();
  // 清除之前的选区
  selection.removeAllRanges();
  // 将新的 Range 对象添加到选区中
  selection.addRange(range);
  if (messageRef.value.innerHTML !== "") {
    messageRef.value.classList.add("has-content");
  } else {
    messageRef.value.classList.remove("has-content");
  }
};
const handleInput = (e) => {
  let value = e.target.innerHTML;
  if (value) {
    e.target.classList.add("has-content");
  } else {
    e.target.classList.remove("has-content");
  }
};

const changeFocusArea = (flag) => {
  textareaisFocus.value = flag;
};

const handleChangeEmoji = () => {
  showEmoji.value = !showEmoji.value;
};

const handleUpload = ({ file }) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = (e) => {
    console.log(e.target.result);
    ImgList.value.push(e.target.result);
  };
};
const handleBeforeUpload = (file) => {
  console.log(file, "file");
};

const deleteImg = (item) => {
  ImgList.value = ImgList.value.filter((img) => img != item);
};

const handleAddLink = () => {
  if (!link.value) {
    return;
  }
  LinkList.value.push(link.value);
  link.value = "";
  showLink.value = false;
};

const deleteLink = (item) => {
  LinkList.value = LinkList.value.filter((link) => link != item);
};

const handleLinkShow = () => {
  console.log(22);
  showLink.value = !showLink.value;
};

// 提交
const handleonSubmit = async () => {
  console.log(111);
  const requestObj = {
    content: messageRef.value.innerHTML,
    istop: 1,
  };
  // 处理图片
  if (ImgList.value.length > 0) {
    if (ImgList.value.length === 1) {
      requestObj.imgUrl = ImgList.value[0];
    } else {
      requestObj.imgUrl = ImgList.value;
    }
    if (requestObj.imgUrl instanceof Object) {
      requestObj.imgUrl = requestObj.imgUrl.map((item) => {
        console.log(item, "item");
        return ChangeBaseToBlob(item);
      });
    } else {
      requestObj.imgUrl = ChangeBaseToBlob(requestObj.imgUrl);
    }
  }
  // 处理链接
  if (LinkList.value.length > 0) {
    if (LinkList.value.length === 1) {
      requestObj.link = LinkList.value[0];
    } else {
      requestObj.link = LinkList.value.join(",");
    }
  }
  if ($store.state.user.userInfo.id) {
    requestObj.userId = $store.state.user.userInfo.id;
  }
  console.log(requestObj, "@@@");
  requestObj.istop = 1;
  if (qzId.value) {
    requestObj.groupId = qzId.value;
  }
  const res = await addTalk(requestObj);
  console.log(res, "add-response");
  messageRef.value.innerHTML = "";
  ImgList.value = [];
  qzId.value = null;
  qzText.value = "请选择圈子";
  getNewsList();
};

const handleChangeGroupId = (code) => {
  groupId.value = code;
  console.log(groupId.value, "code");
  getNewsList({ groupId: groupId.value });
};

// 圈子id变化
const handeChangeQz = (value) => {
  qzText.value = TalkEnumList.value.find(
    (item) => item.enumCode == value
  ).enumText;
};
</script>

<template>
  <div class="container">
    <div class="left">
      <ul>
        <li
          v-for="item in talkTypeList"
          :key="item.id"
          @click="handleChangeGroupId(item.enumCode)"
          :class="{ selectQuanzi: item.enumCode === groupId ? true : false }"
        >
          {{ item.enumText }}
        </li>
      </ul>
    </div>
    <div class="right">
      <el-card>
        <div class="textarea-box" :class="{ active: textareaisFocus }">
          <div
            ref="messageRef"
            id="textarea"
            contenteditable="true"
            placeholder="快和小伙伴们一起分享新鲜事！告诉你个小秘密，发布瞬间时添加圈子会被更多小伙伴们看到哦！"
            @input="handleInput"
            @focus="changeFocusArea(true)"
            @blur="changeFocusArea(false)"
          ></div>
          <el-dropdown class="drop" trigger="click">
            <el-button icon="orange">{{ qzText }}</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-select
                    placeholder="请选择"
                    width="200"
                    @change="handeChangeQz"
                    v-model="qzId"
                  >
                    <el-option
                      v-for="item in TalkEnumList"
                      :key="item.id"
                      :label="item.enumText"
                      :value="item.enumCode"
                    />
                  </el-select>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <div class="extra">
            <template v-if="ImgList.length > 0">
              <div class="pics">
                <div class="pic" v-for="item in ImgList" :key="item">
                  <img :src="item" alt="" />
                  <el-icon @click="deleteImg(item)"><CloseBold /></el-icon>
                </div>
                <el-upload
                  :show-file-list="false"
                  list-type="picture"
                  :http-request="handleUpload"
                  :before-upload="handleBeforeUpload"
                >
                  <div class="upload">
                    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                  </div>
                </el-upload>
              </div>
            </template>
            <!-- 链接 -->
            <template v-if="LinkList.length > 0">
              <div v-for="item in LinkList" :key="item" class="link-item">
                <div class="left">
                  <el-icon
                    ><Link style="width: 1.5em; height: 1.5em"
                  /></el-icon>
                </div>
                <div class="info">
                  <p>{{ item }}</p>
                  <p>{{ item }}</p>
                </div>
                <el-icon @click="deleteLink(item)" class="delete"
                  ><CloseBold
                /></el-icon>
              </div>
            </template>
          </div>
        </div>
        <div class="bottom">
          <div class="action">
            <span @click="handleChangeEmoji" :class="{ active: showEmoji }"
              ><svg-icon name="emoil"></svg-icon>表情</span
            >
            <el-upload
              :show-file-list="false"
              :http-request="handleUpload"
              :before-upload="handleBeforeUpload"
            >
              <span><svg-icon name="pic"></svg-icon> 图片</span>
            </el-upload>
            <span><svg-icon name="code"></svg-icon> 代码</span>
            <el-popover
              placement="bottom-start"
              :width="300"
              trigger="click"
              popper-class="link-popper"
              :visible="showLink"
            >
              <template #reference>
                <span @click="handleLinkShow"
                  ><svg-icon name="link"></svg-icon> 链接</span
                >
              </template>
              <template #default>
                <div class="popover-content">
                  <el-input
                    placeholder="输入网页链接"
                    clearable
                    v-model="link"
                  ></el-input>
                  <div class="tip">
                    <div class="tip-left">自动抓取网页链接的标题和头图</div>
                    <div class="tip-right" @click="handleAddLink">
                      <el-icon><Plus /></el-icon> 添加
                    </div>
                  </div>
                </div>
              </template>
            </el-popover>
          </div>
          <div class="submit">
            <el-button type="primary" @click="handleonSubmit">发布</el-button>
          </div>
        </div>
      </el-card>

      <div class="news">
        <NewsItem v-for="item in newsList" :key="item.id" :newsItem="item" />
      </div>
      <div class="emoji" v-if="showEmoji">
        <Emoji @changeEmoji="getEmoji" />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.container {
  display: flex;
  margin: 0 auto;
  width: 70%;
  margin-top: 30px;
  .left {
    border-radius: 5px;
    position: sticky;
    height: 100%;
    top: 30px;
    margin-right: 25px;
    padding: 10px;
    width: 20%;
    background-color: #fff;
    li {
      border-radius: 5px;
      cursor: pointer;
      padding: 8px;
      margin-bottom: 20px;
      transition: all 0.3s ease;
      &:hover {
        background: #c3c3c3;
        color: #45c8fc;
      }
      &.selectQuanzi {
        background: #c3c3c3;
        color: #45c8fc;
      }
    }
  }
  .right {
    position: relative;
    overflow: auto;
    flex: 1;
    .news {
      margin-top: 20px;
    }
    .emoji {
      position: absolute;
      left: 10px;
      top: 300px;
    }
    .extra {
      // display: flex;
      margin-left: 10px;
      margin-top: 10px;
      margin-bottom: 20px;
      .pics {
        display: flex;
      }
      .pic {
        width: 75px;
        height: 75px;
        margin-right: 10px;
        position: relative;
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        .el-icon {
          cursor: pointer;
          background: rgb(0 0 0 / 40%);
          border-radius: 50%;
          border: 1px solid #c5c5c5;
          position: absolute;
          right: 2px;
          top: 2px;
          svg {
            color: #fff;
          }
          &:hover {
            opacity: 0.8;
          }
        }
      }
      .upload {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 75px;
        height: 75px;
        background-color: #fff;
        .el-icon.avatar-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          width: 28px;
          height: 28px;
          text-align: center;
        }
      }

      .link-item {
        margin-top: 10px;
        position: relative;
        width: 40%;
        display: flex;
        padding: 10px;
        // border:1px solid red;
        background-color: #fff;
        .left {
          margin-right: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 40px;
          height: 40px;
          background-color: rgb(0, 115, 255);
          svg {
            color: #fff;
          }
          :deep .el-icon {
            font-size: 20px;
          }
        }
        .info {
          p {
            font-size: 14px;
          }
          p:first-child {
            font-size: 16px;
            font-weight: 600;
          }
        }
        .delete {
          cursor: pointer;
          background: #f2f3f5;
          border-radius: 50%;
          width: 15px;
          height: 15px;
          padding: 2px;
          border: 1px solid #c4c5ca;
          position: absolute;
          right: 2px;
          top: 2px;
          opacity: 0.8;
          transition: all 0.5s ease;
          &:hover {
            opacity: 1;
          }
        }
      }
    }
  }
}

@media screen and (max-width: 1000px) {
    .container {
      width:100%;
      padding:0 10px;
      .left {
        display: none;
      }
    }
}
:deep .el-select .el-input__wrapper {
  width: 200px;
  cursor: pointer;
}
:deep .el-dropdown-menu__item {
  padding: 0;
}
.textarea-box {
  min-height: 150px;
  position: relative;
  background-color: #f2f3f5;
  border: 1px solid transparent;
  transition: all 0.5s ease;
  &.active {
    background-color: #fff;
    border: 1px solid pink;
  }
  #textarea {
    position: relative;
    min-height: 150px;
    padding: 10px;
    padding-bottom: 50px;
    transition: all 0.2s ease;
    border-radius: 5px;
    &::after {
      font-size: 14px;
      content: attr(placeholder);
      color: #666;
      position: absolute;
      top: 10px;
    }
    &.has-content::after {
      display: none;
    }
  }

  // 选择圈子
  .drop {
    margin-left: 10px;
  }
  .el-button {
    font-size: 12px;
    border-top-left-radius: 25px;
    border-bottom-right-radius: 25px;
    border-top-right-radius: 25px;
    border-bottom-left-radius: 5px;
    padding: 0 10px;
    color: #1e80ff;
  }
}
//操作
.bottom {
  position: relative;
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  .action {
    display: flex;

    span {
      display: flex;
      cursor: pointer;
      margin-right: 20px;
      :deep svg {
        vertical-align: -3px;
        margin-right: 5px;
      }
      &.active {
        color: $strong;
        :deep svg {
          fill: $strong;
        }
      }
      &:hover {
        color: $strong;
        :deep svg {
          fill: $strong;
        }
      }
    }
  }
}

.link-popper {
  .tip {
    margin-top: 13px;
    display: flex;
    justify-content: space-between;
    .tip-right {
      cursor: pointer;
      display: flex;
      align-items: center;
      color: #1e80ff;
      :deep svg {
        color: #1e80ff;
      }
    }
  }
}
</style>
